這篇主要以抓「臺灣證券交易所」的「除權除息計算結果表」為主
目標是從臺灣證券交易所的「除權除息計算結果表」取得每日的 CSV 檔
note: 本資訊自民國92年5月5日起提供

從上面已經知道,只提供 2003-05-05 之後的檔案

下載「除權除息計算結果表」時,資料日期可以直接從 2003-05-05 直接抓到最新一天,需留意時間範圍太大時,可能會遇到 read_timeout ,可選擇時間範圍別抓這麼廣,或把 read_timeout 時間拉長
# app/features/twse/twt_49u/download.rb
module Twse::Twt49u
  class Download
    include Twse::Helpers
    def execute
      current_time = Time.current
      puts "#{self.class}, start_time: #{current_time.to_s}"
      start_date = find_latest_data_date(current_time)
      return puts "#{self.class}, 已經是最新的資料" if start_date == false
      data_path = Rails.root.join("data/twse/TWT49U")
      file_path = data_path.join("TWT49U_#{start_date.strftime("%Y%m%d")}_#{current_time.strftime("%Y%m%d")}.csv")
      return if File.exists?(file_path)
      FileUtils.mkdir_p(data_path) unless File.directory?(data_path)
      download_file(start_date, current_time, data_path, file_path)
      upload_to_github
      puts "#{self.class}, done_time:#{Time.current}, #{(Time.current - current_time).to_s} sec"
    rescue StandardError => e
      puts "errors: #{e.inspect}, backtrace: #{e.backtrace}"
    end
    private
    def find_latest_data_date(current_time)
      latest_data_date = ExStock.latest_data_date
      if latest_data_date
        return false if latest_data_date == current_time
        latest_data_date + 1.day
      else
        Date.parse("2003-05-05") # 僅支援抓 2003-05-05 之後的資料
      end
    end
    def download_file(start_date, current_time, data_path, file_path)
      remote_file = Down::NetHttp.download(
        "#{BASE_URL}exchangeReport/TWT49U?response=csv&strDate=#{start_date.strftime("%Y%m%d")}&endDate=#{current_time.strftime("%Y%m%d")}",
        read_timeout: 120,
      )
      if remote_file.size < 3
        FileUtils.rm_rf(remote_file.path)
      else
        FileUtils.mv(remote_file.path, data_path.join(file_path.basename.to_s))
      end
    end
  end
end
find_latest_data_date 中的 ExStock 為建立的 Model,這篇可以先略過,下一篇會說明 DB 的設計
有了處理「每日收盤行情」的經驗後,在處理類似的資料時,會比較快些
鐵人賽文章連結:https://ithelp.ithome.com.tw/articles/10272820
medium 文章連結:https://link.medium.com/FasXk7JuTjb
本文同步發布於 小菜的 Blog https://riverye.com/
備註:之後文章修改更新,以個人部落格為主